#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    //设置根节点的名称
    ui->treeWidget->setHeaderLabel("食物");
    //添加顶层节点
    QTreeWidgetItem* item1 = new QTreeWidgetItem();
    item1->setText(0, "蔬菜");
    ui->treeWidget->addTopLevelItem(item1);

    QTreeWidgetItem* item2 = new QTreeWidgetItem();
    item2->setText(0, "水果");
    ui->treeWidget->addTopLevelItem(item2);
}

Widget::~Widget()
{
    delete ui;
}

//添加顶层元素
void Widget::on_pushButton_topItem_add_clicked()
{
    //获取输入框的文本内容
    const QString& str = ui->lineEdit->text();
    if(str.isEmpty())
        return;

    //设置到顶层节点
    QTreeWidgetItem* item = new QTreeWidgetItem();
    item->setText(0, str);
    ui->treeWidget->addTopLevelItem(item);
}

//添加到选中元素
void Widget::on_pushButton_item_add_clicked()
{
    //获取输入框中的本文内容
    const QString& str = ui->lineEdit->text();
    if(str.isEmpty())
        return;

    //获取选中元素
    QTreeWidgetItem* item = ui->treeWidget->currentItem();
    if(item == nullptr)
        return;

    //添加节点
    QTreeWidgetItem* new_item = new QTreeWidgetItem();
    new_item->setText(0, str);
    item->addChild(new_item);
    //设置展开父节点
    item->setExpanded(true);
}

//删除选中元素
void Widget::on_pushButton_item_del_clicked()
{
    //获取选中元素
    QTreeWidgetItem* item = ui->treeWidget->currentItem();
    if(item == nullptr)
        return;

    //获取父元素
    QTreeWidgetItem* parent = item->parent();
    //如果是顶层节点的话
    if(parent == nullptr)
    {
        //获取下标
        int index = ui->treeWidget->indexOfTopLevelItem(item);
        //删除
        ui->treeWidget->takeTopLevelItem(index);
    }
    //非顶层节点
    else
    {
        parent->removeChild(item);
    }
}
